<?php

declare(strict_types=1);

namespace App\Controller\Safepay\V2\Orders;

use App\Controller\Safepay\V2\Controllers;
use App\Request\Orders\Order as OrderRequest;
use App\Services\Orders\Order as OrderServices;
use Psr\Http\Message\ResponseInterface;
use App\Services\Orders\Invoice as InvoiceServices;
use function Hyperf\Translation\__;

/**
 * Class Order
 * @author zx
 * @package App\Controller\Safepay\V2\Orders
 */
class Order extends Controllers
{
    /**
     * 请求类
     * @var string
     */
    protected string $requestClass = OrderRequest::class;

    public function __construct(
        OrderServices $orderServices,
        protected InvoiceServices $invoiceServices
    )
    {
        parent::__construct();
        $this->services = $orderServices;
    }

    /**
     * 订单发货
     * @return ResponseInterface
     */
    public function delivery():ResponseInterface
    {
        $input = $this->input(['delivers']);

        $shippingMap = [
            'STO' => '申通',
            'SF' => '顺丰',
            'ZTO' => '中通快递',
            'YUNDA' => '韵达',
            'YTO' => '圆通',
            'JITU' => '极兔速递'
        ];

        $invoiceData = [];
        foreach ($input['delivers'] as $deliver) {
            $shippingCode = '';
            foreach ($shippingMap as $key => $shipping) {
                if (false !== stripos(strtoupper($key), strtoupper($deliver['shipping_code']))) {
                    $shippingCode = $key;
                    break;
                }
            }
            if (!$shippingCode) {
                continue;
            }
            /** @var \App\Model\Orders\Order $orderModel */
            $orderModel = $this->services->findBy('paid_no', $deliver['no']);
            if (!$orderModel) {
                continue;
            }
            $invoiceData[] = [
                'order_id' => $orderModel->id,
                'shop_id' => $orderModel->shop_id,
                'consignee' => $orderModel->consignee,
                'mobile' => $orderModel->mobile,
                'prov' => $orderModel->prov,
                'city' => $orderModel->city,
                'area' => $orderModel->area,
                'address' => $orderModel->address,
                'logistics_code' => $shippingCode,
                'logistics_name' => $shippingMap[$shippingCode],
                'postage_amount' => $orderModel->postage_amount,
                'logistics_no' => $deliver['logistics_no']
            ];
        }

        if (!$invoiceData) {
            return failed(__('message.element.empty'));
        }

        $invoiceModels = $this->invoiceServices->createAll($invoiceData);
        if ($invoiceModels->isEmpty()) {
            return internalError();
        }

        return stored();
    }
}
